<template>
  <div class="common-layout">
    <div class="searchBox">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline" size="default">
        <el-form-item>
          <el-input v-model="searchForm.title" placeholder="任务名称" />
        </el-form-item>
        <el-form-item>
          <el-input v-model="searchForm.task_id" placeholder="任务id" />
        </el-form-item>
        <el-form-item>
          <el-date-picker v-model="searchForm.createtime" end-placeholder="End date" range-separator="To"
            start-placeholder="Start date" type="daterange" unlink-panels />
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.style" clearable placeholder="风格">
            <el-option v-for="(item, index) in styleOptions.data" :key="index" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.status" clearable placeholder="状态">
            <el-option v-for="(item, index) in statusOptions" :key="index" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button :icon="Search" :loading="loading" size="small" type="success" @click="getAll(false)">查询
          </el-button>
          <el-button :icon="Plus" size="small" type="success" @click="goRouter('batchCreate/addTask', {})">添加任务
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- <div class="mainBox" v-infinite-scroll="loadMoreTask" :infinite-scroll-delay="1000"> -->
    <div class="main" v-infinite-scroll="loadMoreTask" infinite-scroll-distance="100">
      <div class="taskItem" v-for="taskItem in tableData.data">
        <p class="taskNum">{{ '图片数量：' + taskItem.req_json.num }}</p>
        <span :class="taskItem.status_0 >= 2 ? 'paintStatus succesStatus' : 'paintStatus '"
          @click="goRouter('batchCreate/checkTask', taskItem)">
          <img :src="taskItem.icon" alt="">
          <p>{{ mateStatus(taskItem.status_0) }}</p>
          <p>{{ mateProgress(taskItem.status_0) }}</p>
          <span class="mask" v-if="taskItem.status_0 < 2"></span>
        </span>
        <!-- 任务名称和id -->
        <span class="taskName taskInfo">
          <!-- <p>{{ taskItem.title }}</p> -->
          <el-popover placement="top" title="提示词" :width="200" trigger="hover">
            <template #reference>
              <p>{{ taskItem.title.substring(0, 10) + '...' }}</p>
            </template>
            <p>{{ taskItem.title }}</p>
          </el-popover>

          <el-popover placement="top" title="任务id" :width="200" trigger="hover">
            <template #reference>
              <p>{{ taskItem.task_id.substring(taskItem.task_id.length - 6) + '...' }}</p>
            </template>
            <p>{{ taskItem.task_id }}</p>
          </el-popover>
        </span>
        <span class="taskStyle taskInfo">
          <p>{{ mateStyle(taskItem.style_id) }}</p>
          <p>{{ dateFormat(taskItem.createtime, true) }}</p>
        </span>
        <span class="itemBtn taskInfo">
          <button @click="goRouter('batchCreate/addTask', taskItem)">复制</button>
          <button @click="delImg(taskItem)">清空图片</button>
          <!-- <button @click="changeStatus(taskItem.task_id, 4)">删除记录</button> -->
        </span>
      </div>
      <div class="taskItemTemp"> </div>
      <div class="taskItemTemp"> </div>
      <div class="taskItemTemp"> </div>
      <div class="taskItemTemp"> </div>

    </div>
    <!-- </div> -->



  </div>
</template>
<script setup lang="ts">
import {
  ref,
  reactive,
  getCurrentInstance,
  onMounted,
  onUnmounted,
  toRefs,
  toRaw,
} from "vue";
import { useRouter } from "vue-router";
import { Search, Plus } from "@element-plus/icons-vue";
import router from '../../../router';
import $apiFun from "../../../request/api";
import { ElMessage } from 'element-plus'
import { dateFormat } from "../../../utils/formatter";
//定义要发送的emit事件
const emit = defineEmits(['openLogin'])
const searchForm = ref({}) as any//搜索条件
const loading = ref(false);//搜索状态
//风格模型
const styleOptions = reactive({ data: [] }) as any;
const page = ref(0)//分页
const tableData = reactive({
  data: [] as any,
});//所有任务
const notDataCount = ref(0)//所有数据全部加载结束
const waitTaskList = reactive([] as any)//未完成的任务列表
let taskTime = 0 as any; //任务轮询定时器

//匹配模型风格
const mateStyle = (style_id: number) => {
  let name = "";
  styleOptions.data.forEach((val: any) => {
    if (val.id == style_id) name = val.name;
  });
  !!name ? "" : name = "风格已下线";
  return name
};
onMounted(() => {
  getStyle();
  // getAll(false);
});
//状态选项
const statusOptions = reactive([
  {
    label: "生成中",
    value: 1,
  },
  {
    label: "已完成",
    value: 2,
  },
  {
    label: "已领取",
    value: 3,
  }
]);
//匹配状态
const mateStatus = (status: number) => {
  let label = '生成中'
  statusOptions.forEach(element => {
    if (element.value == status) label = element.label
  });
  return label
};
//匹配进度
const mateProgress = (status: number) => {
  if (status < 1) {
    return (status * 100).toFixed(2) + "%"
  } else if (status > 1) {
    return "100%"
  } else return '获取进度中'
};
const openLoginFun = () => {
  emit('openLogin', true)
}
//获取风格模型
const getStyle = () => {
  $apiFun.Model2({ channel: 6 }).then((res: any) => {
    if (res.code == 1001) {
      openLoginFun
      return
    }
    console.log('获取风格模型', res);
    styleOptions.data = res.data;
  });
};
//删除任务图片
const delImg = (data: any) => {
  console.log(data)
  $apiFun.delImgsInOss({ task_id: data.task_id }).then((res: any) => {
    console.log('删除任务图片', res)
    if (res.code == 200) {
      ElMessage({
        message: '云文件删除成功',
        type: 'success',
      })
    } else {
      ElMessage({
        message: '云文件删除失败，请等候生成完成或强制删除',
        type: 'error',
      })
    }

  })

}
//更新任务状态
const changeStatus = (task_id: string, status: number) => {
  $apiFun.upTaskStatus({ spec: { status_0: status, task_id: task_id } }).then((res: any) => {
    console.log(res)
    if (status == 4) {
      tableData.data.forEach((val: any, index: any) => {
        if (val.task_id == task_id) {
          tableData.data.splice(index, 1)
        }
      })
    }
  })
}
//获取更多数据
const loadMoreTask = async () => {
  //不在加载才能继续
  if (!loading.value) {
    page.value++
    if (notDataCount.value == 0) {
      await getAll(true)
    } else if (notDataCount.value == 1) {
      ElMessage.success('已加载全部数据')
      notDataCount.value++
    }
  }

}
//查询所有数据
const getAll = (addFlag: boolean) => {
  loading.value = true
  $apiFun.allTask({ type: 2, channel: 'official-website', page: page.value }).then((res: any) => {
    console.log(res)
    if (res.code == 1001) {
      emit('openLogin', true)
      return
    }
    if (res.code == 200) {
      console.log("查询任务列表", res);
      if (res.data.count == 0) {
        notDataCount.value++
      }
      //分页请求，累加数据
      if (addFlag) {
        tableData.data.push(...res.data.tasks)
      } else {
        //首次请求，清空旧数据
        // 清空未完成的数组
        waitTaskList.splice(0, waitTaskList.length)
        tableData.data = res.data.tasks;
      }
      //筛选条件
      for (let index = tableData.data.length - 1; index >= 0; index--) {
        const element = tableData.data[index];
        if (searchForm.value.title && element.title != searchForm.value.title) {
          tableData.data.splice(index, 1)
          continue
        }
        if (searchForm.value.task_id && element.task_id != searchForm.value.task_id) {
          tableData.data.splice(index, 1)
          continue
        }
        if (searchForm.value.createtime && (element.createtime < searchForm.value.createtime[0] || element.createtime > searchForm.value.createtime[1])) {
          tableData.data.splice(index, 1)
          continue
        }
        if (searchForm.value.style && element.style_id != searchForm.value.style) {
          tableData.data.splice(index, 1)
          continue
        }
        if (searchForm.value.status && element.status_0 != searchForm.value.status) {
          tableData.data.splice(index, 1)
          continue
        }
        try {
          element.req_json = JSON.parse(element.req_json)
        } catch (error) { }
        //未完成任务
        if (element.status_0 < 2) {
          waitTaskList.push(element.task_id)
        }
      };
      rotateTaskInfo(0)
      loading.value = false

    }

  })
}
//查询批量创作数据及绘画进度
let rotateTaskInfo = async (index: number) => {
  //清除轮询任务列表定时器
  clearTimer();
  // 存在未完成任务，2000ms轮询一次
  if (waitTaskList.length > 0) {
    //查询任务
    const flag = await getTaskInfo(waitTaskList[index])
    taskTime = setTimeout(() => {
      index++
      if (flag) index--
      if (index == waitTaskList.length) index = 0
      rotateTaskInfo(index);
    }, 2000);
  }
};
//获取任务信息
const getTaskInfo = async (task_id: string) => {
  let flag = false
  await $apiFun.ScriptProgress({ task_id: task_id }).then((res: any) => {
    console.log('getTaskInfo', task_id, res)
    if (res.code == 200) {
      if (res.data.progress == 1) {
        //任务已完成，删除待完成
        waitTaskList.splice(waitTaskList.indexOf(task_id), 1);
        //修改表格数据
        tableData.data.forEach((element: any) => {
          element.task_id == task_id ? element.status_0 = 2 : ''
        })
        flag = true
      } else {
        tableData.data.forEach((element: any) => {
          if (element.task_id == task_id) {
            element.status_0 = res.data.progress
          }
        });
      }
    }
  })
  return flag
}
// 页面销毁，去除查询服务器状态定时器
onUnmounted(() => {
  console.log('钩子销毁，移除定时器')
  clearTimer()
})
//清除轮询任务列表定时器
const clearTimer = () => {
  clearTimeout(taskTime);
  taskTime = 0;
};
//路由跳转
const goRouter = (url: string, data: any) => {

  if (data.status_0 < 2) {
    ElMessage.info("请等待生成完成后再点击")
    return
  }
  if (data.status_0 == 2) {
    changeStatus(data.task_id, 3)
  }
  router.push({
    name: url,
    query: {
      title: data.title || null,
      num: data.req_json?.num || null,
      style_id: data.style_id || null,
      size: data.req_json?.img_size || null,
      negative_prompt: data.req_json?.negative_prompt || null,
      task_id: data.task_id || '',
    },
  });

};



</script>


<!-- 内容区 -->
<style scoped>
/* 页脚 */
.example-pagination-block,
.example-pagination-block {
  margin-top: 10px;
  float: right;
}

:deep(.btn-prev),
:deep(.el-pagination button),
:deep(.el-pager .number) {
  background-color: transparent;
}

:deep(.el-pager li.is-active) {
  color: rgba(255, 226, 41, 1);
}

:deep(.el-pager li:hover) {
  color: rgba(255, 226, 41, 1);
}

.example-pagination-block,
.example-demonstration {
  margin-bottom: 16px;
}

.taskInfo {
  margin: 4px 0;
}

/* .taskInfo p {
  width: 30%;
  text-align: left;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
} */

.itemBtn {
  display: flex;
  justify-content: space-around;
}

.itemBtn button {
  cursor: pointer;
  width: 30%;
  height: 29px;
  opacity: 1;
  border-radius: 20px;
  background: rgba(255, 255, 255, 1);
  border: 1px solid rgba(255, 195, 0, 1);
  font-size: 12px;
  font-weight: 400;
  color: rgba(166, 166, 166, 1);
}

.taskName,
.taskStyle {
  position: relative;
  display: block;
  height: 20px;
}

.taskItem .taskStyle p:nth-child(1) {
  color: rgba(128, 128, 128, 1);
  font-weight: 400;
}

.taskName p:nth-child(1),
.taskStyle p:nth-child(1) {
  position: absolute;
  left: 0;
  font-size: 12px;
  font-weight: 700;
  color: rgba(0, 0, 0, 1);
}

.taskName p:nth-child(2),
.taskStyle p:nth-child(2) {
  position: absolute;
  right: 0;
  font-size: 12px;
  font-weight: 400;
  color: rgba(128, 128, 128, 1);
}


.paintStatus p {
  position: absolute;
  bottom: 5px;
  z-index: 999;
}

.paintStatus p:nth-child(2) {
  left: 4px;
  font-size: 14px;
  color: rgba(73, 230, 136, 1);
}

.paintStatus p:nth-child(3) {
  right: 4px;
  font-size: 14px;
  color: rgba(255, 255, 255, 1);

  font-size: 14px;
  font-weight: 500;
  color: rgba(255, 255, 255, 1);

}

.taskItem .succesStatus p:nth-child(2) {
  font-size: 14px;
  font-weight: 500;
  color: rgba(73, 230, 136, 1);
}


.paintStatus {
  position: relative;
  bottom: 0;
  cursor: pointer;
}

.mask {
  position: absolute;
  display: block;
  bottom: 0;
  width: 100%;
  aspect-ratio: 1/1;
  opacity: 1;
  border-radius: 10px;
  background: linear-gradient(0deg, rgba(56, 56, 56, 1) 0%, rgba(56, 56, 56, 0) 100%);
}

.taskItem img {
  width: 100%;
  aspect-ratio: 1/1;
  border-radius: 10px;
}

.taskItemTemp {
  /* max-width: 300px; */
  width: 18%;
}

.taskNum {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 10;
  background-color: rgba(255, 195, 0, 1);
}

.taskItem {
  position: relative;
  /* max-width: 300px; */
  text-align: center;
  /* display: inline-block; */
  width: 18%;
  margin-bottom: 20px;
  /* height: 40%; */
  /* aspect-ratio: 1/1; */
  box-sizing: border-box;
  padding: 10px;
  border-radius: 10px;
  background: rgba(255, 255, 255, 1);
  box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.15);

}

.main {
  display: flex;
  justify-content: space-between;
  width: 100%;
  flex-wrap: wrap;
  box-sizing: border-box;
  height: 80%;
  overflow-y: auto;
}

.mainBox {
  width: 100%;
  height: 80%;
  background-color: red;
}
</style>
<!-- 搜索区 -->
<style scoped>
.searchBox button {
  width: 100px;
  height: 31px;
  opacity: 1;
  border-radius: 15px;
  background: rgba(255, 226, 41, 1);
  border: 0px;
  color: rgba(56, 56, 56, 1);
}

.searchBox {
  width: 96%;
}

.common-layout {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 20px;
  padding-right: 80px;
  background-color: #fafafa;
}
</style>
